// pages/myCenter/liveActivity/creatStep/index.js
import Common from '../../../../common/common';
let common = new Common;
import moment from '../../../../common/moment';

const app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEdit: 0, //0新增 1编辑
    isPromise: 0, //阅读协议
    uuid: '', //重新提交的时候带入
    liveActivityInfo: '',
    liveplayerType: 0, //商品投放类型 0实时库存 1投放量
    zbPlanGoods: [], //总部直播商品库
    btnDisable: false,
    nowDate: '', //现在日期
    nowTime: "", //现在时间
    liveDate: '', //直播日期
    imgurl: '',
    showLiveModel: false,
    formData: {
      "name": "", //直播间名称
      "coverImg": "", //背景图
      "startTime": "",
      "endTime": "",
      "anchorName": "", //主播昵称
      "anchorWechat": "", //主播微信号
      "subAnchorWechat": "",
      "createrWechat": "",
      "shareImg": "", //分享图
      "feedsImg": "",
      "isFeedsPublic": 1, //是否开启官方收录 【1: 开启，0：关闭】，默认开启收录
      "type": 0, //直播间类型 【1: 推流，0：手机直播】
      "closeLike": 0,
      "closeGoods": 0,
      "closeComment": 0,
      "closeReplay": 0,
      "closeShare": 0,
      "closeKf": 1,
      "orgSeq": "",
      "storeName": "",
      "backgroundImg": "",
      "coverImgUrl": "",
      "channelImg": ""
    },

    numList: [{
        name: '创建主播'
      },
      {
        name: '挑选直播商品'
      },
      {
        name: '完善直播间'
      }
    ],
    num: 0,
    activityId: "",
    showApproveModel: false, //显示 主播认证二维码
    approveImage: '',
  },
  onLoad: function (options) {
    // let orgSeq = '33c2a493-1261-4190-be30-aaec1ba4c353'; // app.globalData.shopInfo.orgSeq;
    // let storeName = '博智体验店'; // app.globalData.shopInfo.orgName;
    // let name = '博智体验店'; //app.globalData.shopInfo.orgName;

    let orgSeq = app.globalData.shopInfo.orgSeq;
    let storeName = app.globalData.shopInfo.orgName;
    let name = app.globalData.shopInfo.orgName;

    this.setData({
      orgSeq,
      isEdit: Number(options.isEdit) || 0,
      uuid: options.uuid || '',
      [`formData.orgSeq`]: orgSeq,
      [`formData.storeName`]: storeName,
      [`formData.name`]: name,
      activityId: options.activityId
    })

    this.setData({
      nowDate: moment().format('YYYY-MM-DD'),
      nowTime: moment().format('HH:mm'),
    })
    console.log(moment().format('YYYY-MM-DD'));
    console.log(moment().format('HH:mm'));

    //查活动信息
    this.getLiveActivity();
  },
  onReady: function () {},
  getLiveActivity() {
    common.requestAjax("/api/flashsale-service/v1/zbRelatedApi/getZbEntrance", "GET", {
      orgSeq: this.data.orgSeq
    }).then(res => {
      if (res.data.code) {
        let liveActivityInfo = res.data.result || "";
        let startDate = liveActivityInfo.beginTime.split(" ")[0];
        let endDate = liveActivityInfo.endTime.split(" ")[0];
        let liveDate = liveActivityInfo.beginTime.split(" ")[0];
        if (this.data.isEdit == 1) {
          //编辑初始化
          let formData = liveActivityInfo.zbHomeDTOList[0];
          liveDate = formData.startTime.split(" ")[0];
          formData.startTime = formData.startTime.split(" ")[1];
          formData.endTime = formData.endTime.split(" ")[1];

          this.setData({
            formData,
            chooseGoodList: liveActivityInfo.zbPlanOrgGoodsDTOS
          })
        } else {
          //新增初始化
          let formData = this.data.formData;
          formData.startTime = liveActivityInfo.beginTime.split(" ")[1];
          if (liveActivityInfo.beginTime.split(" ")[0] == liveActivityInfo.endTime.split(" ")[0]) {
            //活动设置的直播开始时间和结束时间为同一天。则取结束时间的时分秒
            formData.endTime = liveActivityInfo.endTime.split(" ")[1];
          } else {
            //若非同一天。则直播的结束时间取23：59
            formData.endTime = "23:59:00"
          }
          this.setData({
            formData
          })
        }

        this.setData({
          liveDate,
          endDate,
          startDate,
          liveActivityInfo
        })

        //查询直播商品库
        this.getZbPlanGoods()

      }
    })
  },
  setZbOrgGoods() {
    let data = [];
    this.data.zbPlanGoods.forEach(item => {
      if (item.checked) {
        item.orgSeq = this.data.orgSeq;
        item.status = 1;
        item.planOrgId = this.data.liveActivityInfo.uuid
        data.push(item)
      }
    })
    console.log(data);
    common.requestAjax("/api/flashsale-service/v1/zbRelatedApi/zbOrgGoods", "POST", data).then(res => {
      wx.hideLoading()
      this.setData({
        btnDisable: false,
      })

      if (res.data.code) {
        this.setData({
          num: this.data.num == this.data.numList.length - 1 ? 0 : this.data.num + 1
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
      }
    })
  },
  changeChecked(e) {
    let index = Number(e.currentTarget.dataset.index);
    let goodsList = this.data.zbPlanGoods;
    goodsList[index].checked = !goodsList[index].checked;
    this.setData({
      zbPlanGoods: goodsList
    })
  },
  /** 
   * 选择商品投放类型
   * 0 实时库存  1投放量
   */
  changeLiveplayerType(e) {
    let type = Number(e.detail.value);
    let goodsList = this.data.zbPlanGoods;
    if (type == 0) {
      goodsList.forEach(item => {
        item.goodsStock = 0;
        item.currentStock = 0;
      })
    }
    this.setData({
      liveplayerType: type,
      zbPlanGoods: goodsList
    })
  },
  changeNum(e) {
    let index = e.currentTarget.dataset.index;
    let num = Number(e.detail.value);
    if (this.data.zbPlanGoods[index].bizStock >= num) {
      this.setData({
        [`zbPlanGoods[${index}].goodsStock`]: num,
        [`zbPlanGoods[${index}].currentStock`]: num
      })
    } else {
      this.setData({
        [`zbPlanGoods[${index}].goodsStock`]: this.data.zbPlanGoods[index].bizStock,
        [`zbPlanGoods[${index}].currentStock`]: this.data.zbPlanGoods[index].bizStock
      })
      wx.showToast({
        title: '投放量不能大于实际库存',
        icon: 'none'
      })
    }
  },
  //上传图片
  uploadImage(e) {

    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFiles;
        console.log('tempFilePaths', tempFilePaths);
        wx.showLoading({
          title: '图片上传中',
          icon: 'none'
        })
        wx.uploadFile({
          url: `${common.requestApi}/api/file-service/v1/zbHomeApi/uploadFileByWX?type=image`,
          filePath: tempFilePaths[0].path,
          header: {
            "token": wx.getStorageSync('token')
          },
          name: 'file',
          formData: {},
          success: res => {
            let respon = JSON.parse(res.data);
            if (respon.code) {
              this.setData({
                imgurl: respon.result.url,
                [`formData.coverImg`]: respon.result.mediaId,
                [`formData.shareImg`]: respon.result.mediaId,
                [`formData.feedsImg`]: respon.result.mediaId,
                [`formData.backgroundImg`]: respon.result.url,
                [`formData.coverImgUrl`]: respon.result.url,
                [`formData.channelImg`]: respon.result.url
              })
            }
          },
          complete: com => {
            wx.hideLoading();
            console.log(com)
          }
        })
      }
    })
  },
  getInputValue(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      btnDisable: false,
      [`formData.${key}`]: e.detail.value.trim()
    })
  },
  changeTime(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      [`formData.${key}`]: e.detail.value + ':00'
    })
  },
  //选择直播日期
  chooseDate(e) {
    this.setData({
      liveDate: e.detail.value
    })
  },
  nextStep() {
    wx.showLoading({
      title: '请稍后...',
      icon: "none"
    })
    this.setData({
      btnDisable: true
    })
    if (this.data.num === 0) {

      if (this.data.isPromise == 1) {
        this.toCreateLiveMan();
      } else {
        this.setData({
          btnDisable: false
        })
        wx.showToast({
          title: '请先阅读《云店直播服务承诺》。',
          icon: 'none'
        })
        return false
      }
    } else if (this.data.num == 1) {
      //设置商品
      if (this.data.zbPlanGoods.length) {
        let noChoose = 0; // 0 一个都没选  
        let noCurrentStock = 0; //1 没有设置投放量的
        let noAuditStatus = 0; //1 有没审核通过的商品
        this.data.zbPlanGoods.forEach(item => {
          if (item.checked) {
            noChoose = 1
          }
          if (item.checked && this.data.liveplayerType == 1 && !item.currentStock) {
            //选中且设置了投放类型为投放量的 数量不能为0 
            noCurrentStock = 1;
          }

          if (item.checked && item.auditStatus != 2) {
            //勾选了审核没通过的商品
            noAuditStatus = 1
          }
        })

        if (noChoose == 1 && noCurrentStock == 1) {
          wx.showToast({
            title: '直播商品投放数量不能为0！',
            icon: 'none'
          })
          this.setData({
            btnDisable: false
          })
          return false;
        } else if (noChoose == 1 && noAuditStatus == 1) {
          if (noAuditStatus == 1) {
            wx.showToast({
              title: '不能选择没有通过审核的商品！',
              icon: 'none'
            })
            this.setData({
              btnDisable: false
            })
            return false;
          }
        } else if (noChoose == 0) {
          wx.showToast({
            title: '请选择直播商品！',
            icon: 'none'
          })
          this.setData({
            btnDisable: false
          })
          return false;
        } else {
          this.setZbOrgGoods();
        }

      } else {
        wx.showToast({
          title: '总部没有设置商品，无法创建直播间',
          icon: "none"
        })
        return false
      }

    } else if (this.data.num == 2) {
      this.creatLiveRoom();
    }
  },
  backStep() {
    this.setData({
      num: this.data.num - 1
    })
  },
  toCreateLiveMan() {
    if (!this.data.formData.anchorWechat) {
      wx.showToast({
        title: "请先填写主播的微信号！",
        icon: "none"
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }

    if (this.data.formData.anchorWechat.length < 6) {
      wx.showToast({
        title: "微信号应大于6位字符或数字！",
        icon: "none"
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }

    common.requestAjax('/api/flashsale-service/v1/zbRelatedApi/zbAnchor', 'POST', {
      "anchorWechat": this.data.formData.anchorWechat,
      "status": 1, //"status":1, 创建，0 删除
      "approvalId": this.data.liveActivityInfo.uuid,
      "orgSeq": this.data.orgSeq
    }).then(res => {
      wx.hideLoading()
      this.setData({
        btnDisable: false,
      })
      if (res.data.code) {
        this.setData({
          num: this.data.num == this.data.numList.length - 1 ? 0 : this.data.num + 1
        })
      } else {
        let errorCode = res.data.message.split(':')[0];
        if (errorCode === "400002") {
          //主播角色需要认证
          this.setData({
            showApproveModel: true,
            approveImage: res.data.result
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: "none"
          })
        }
      }
    })
  },

  creatLiveRoom() {

    if (this.getByteLen(this.data.formData.anchorName) < 4 || this.getByteLen(this.data.formData.anchorName) >= 30) {
      wx.showToast({
        title: '主播昵称长度在2-15个汉字之间！',
        icon: 'none'
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }


    if (!this.data.formData.anchorName) {
      wx.showToast({
        title: '请填写主播昵称！',
        icon: 'none'
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }


    if (!this.data.liveDate) {
      wx.showToast({
        title: '请选择开播日期！',
        icon: 'none'
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }

    if (!this.data.formData.startTime) {
      wx.showToast({
        title: '请选择开播开始时间！',
        icon: 'none'
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }

    if (!this.data.formData.endTime) {
      wx.showToast({
        title: '请选择开播结束时间！',
        icon: 'none'
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }
    let data = JSON.parse(JSON.stringify(this.data.formData));
    data.startTime = this.data.liveDate + " " + this.data.formData.startTime;
    data.endTime = this.data.liveDate + " " + this.data.formData.endTime;


    const nowTime = new Date().getTime();
    const startTime = new Date(data.startTime.replace(/-/g, '/')).getTime();
    const endTime = new Date(data.endTime.replace(/-/g, '/')).getTime();

    if (nowTime >= startTime || startTime - nowTime <= 600000 || startTime >= endTime || endTime - startTime < 1800000) {
      //时间差小于半小时 
      wx.showToast({
        title: '开播时间必须为当前时间10分钟以后,且直播时间不得小于半小时！',
        icon: 'none'
      })
      this.setData({
        btnDisable: false
      })
      return false;
    }

    data.approvalId = this.data.liveActivityInfo.uuid;
    data.planId = this.data.liveActivityInfo.planId;
    console.log(data);

    common.requestAjax("/api/flashsale-service/v1/zbRelatedApi/zbHome", "POST", data).then(res => {
      wx.hideLoading()
      if (res.data.code) {
        //提交该申请
        common.requestAjax("/api/flashsale-service/v1/zbRelatedApi/updatePlanOrg", "POST", {
          "uuid": this.data.liveActivityInfo.uuid,
          "approvalUser": this.data.liveActivityInfo.approvalUser,
          "approvalStatus": 1, //审批状态(0-初始/1-提交审批/2-审批通过/3-审批驳回)
          "approvalComments": this.data.liveActivityInfo.approvalComments,
          "liveplayerType": this.data.liveplayerType,
          "planId": this.data.liveActivityInfo.planId,
          isPromise: 1
        }).then(ress => {
          if (ress.data.code) {
            wx.showToast({
              title: "创建成功,等待总部审批",
              icon: "none"
            })
            setTimeout(() => {
              wx.navigateBack()
            }, 1500);
          } else {
            this.setData({
              btnDisable: false,
            })
            wx.showToast({
              title: ress.data.message,
              icon: "none"
            })
          }
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
      }
    })
  },

  //查询总部商品库列表
  getZbPlanGoods() {
    common.requestAjax("/api/flashsale-service/v1/zbRelatedApi/zbPlanInfo", "GET", {
      planId: this.data.activityId,
      orgSeq: app.globalData.shopInfo.orgSeq
    }).then(res => {
      if (res.data.code) {
        //商品库初始化
        let arrayList = [];
        arrayList = res.data.result.zbPlanGoods;
        if (arrayList && arrayList.length != 0) {
          arrayList.forEach(item => {
            item.uuid = "";
            item.checked = false;
          })
        }
        //若二次修改且 则要去重
        if (this.data.isEdit == 1) {
          this.data.chooseGoodList.forEach(citem => {
            arrayList.forEach(item => {
              if (citem.goodsId === item.goodsId) {
                item.uuid = citem.uuid;
                item.checked = true
              }
            })
          })
        }
        this.setData({
          zbPlanGoods: arrayList
        })
      }
    })
  },
  toReadProtocol() {
    wx.navigateTo({
      url: '/pages/myCenter/liveActivity/protocol/index',
    })
  },
  changeIsPromise() {
    this.setData({
      isPromise: !this.data.isPromise
    })
  },
  getByteLen(val) {
    var len = 0;
    for (var i = 0; i < val.length; i++) {
      var a = val.charAt(i);
      if (a.match(/[^\x00-\xff]/ig) != null) {
        len += 2;
      } else {
        len += 1;
      }
    }
    return len;
  }
})